package ui.swing.longwork;

import ui.swing.common.SwingWorker;

public class LongTask {

	public static final int INTERRUPTED = -1;
	public static final int NEW = 0;
	public static final int ONGOING = 1;
	public static final int FINISHED = 2;
	
	private int lengthOfTask;
	private int current = 0;
	private String statMessage;
	private SwingWorker worker;
	private volatile int status;

	LongTask() {
		// Compute length of task...
		// In a real program, this would figure out
		// the number of bytes to read or whatever.
		lengthOfTask = 1000;
	}

	/**
	 * Called from ProgressBarDemo to start the task.
	 */
	synchronized void go() {
		current = 0;
		worker = new SwingWorker() {
			@Override
			public Object construct() {
				while (current < lengthOfTask) {
					// We must do at least one of the following:
					// 1. Periodically check Thread.interrupted()
					// 2. Periodically sleep or wait
					try {
						Thread.sleep(500); // sleep for a second
						current += Math.random() * 100; // make some progress
						// 下面是第二种：
						// if(Thread.interrupted()) {
						//	System.out.println("操作被用户中断");
						//	throw new InterruptedException();
						// }
						if (current > lengthOfTask) {
							current = lengthOfTask;
						}
						statMessage = "Completed " + current + " out of "
								+ lengthOfTask + ".";
					} catch (InterruptedException e) {
						System.out.println("操作被用户中断");
					}
				}
				status = FINISHED;
				return null;
			}
		};
		worker.start();
		status = ONGOING;
	}

	/**
	 * Called from ProgressBarDemo to find out how much work needs to be done.
	 */
	int getLengthOfTask() {
		return lengthOfTask;
	}

	/**
	 * Called from ProgressBarDemo to find out how much has been done.
	 */
	int getCurrent() {
		return current;
	}
	
	synchronized void interupt() {
		worker.interrupt();
		status = INTERRUPTED;
	}

	int getStatus() {
		return status;
	}

	String getMessage() {
		return statMessage;
	}

}
